package com.jdd.enterprise.domain.service;
import cn.hutool.core.lang.func.Func;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jdd.enterprise.api.vo.DishCategoryVO;
import com.jdd.enterprise.domain.entity.DishCategory;
import com.jdd.enterprise.domain.mapper.CategoryMapper;
import com.jdd.enterprise.exception.FailException;

import org.checkerframework.checker.units.qual.A;
import org.checkerframework.checker.units.qual.C;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PostMapping;

import javax.validation.constraints.Max;
import java.nio.file.attribute.FileAttribute;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@Service
public class CategoryService extends ServiceImpl<CategoryMapper, DishCategory> {
    @Autowired
    private CategoryMapper categoryMapper;
    /*
    这个是搜索列表.没有参数搜全部,有分类名字,就根据分类名字搜
     */
    public List<DishCategoryVO> searchByName(DishCategory param) {
        LambdaQueryWrapper<DishCategory> wrapper = Wrappers.lambdaQuery(DishCategory.class);

        if(StringUtils.isNotBlank(param.getCategoryName())){
            wrapper.like(DishCategory::getCategoryName,param.getCategoryName());
        }
        List<DishCategory> dishCategories = categoryMapper.selectList(wrapper);

        //我不要二级,我只要一节附带二级的形式
        List<DishCategory> oneLevel = dishCategories.stream().filter(one -> one.getParentCode().equals("0")).collect(Collectors.toList());

        int sizeOfOneLevel = oneLevel.size();//TODO



        List<DishCategory> twoLevel = dishCategories.stream().filter(one -> !one.getParentCode().equals("0")).collect(Collectors.toList());

        int sizeOfTwoLevel = twoLevel.size();//TODO




        //然后要把他的儿子塞满!!  那么,如何查询他的儿子,根据parentCode


        List<DishCategoryVO> dishCategoryVOS = new ArrayList<>();



        for (DishCategory dishCategory : oneLevel) {
            DishCategoryVO dishCategoryVO = new DishCategoryVO();
            BeanUtils.copyProperties(dishCategory,dishCategoryVO);
            if(dishCategory.getHasChildrenFlag()){
                String categoryCode = dishCategory.getCategoryCode();
                List<DishCategory> children = twoLevel.stream().filter(one -> one.getParentCode().equals(categoryCode)).collect(Collectors.toList());
                dishCategoryVO.setChildren(children);
            }
            dishCategoryVOS.add(dishCategoryVO);

        }






        return dishCategoryVOS;
    }
    public List<DishCategory> selectOneLevelCategories() {
        LambdaQueryWrapper<DishCategory> wrapper = Wrappers.lambdaQuery(DishCategory.class);
        wrapper.eq(DishCategory::getParentCode,0);
        return  categoryMapper.selectList(wrapper);
    }
    /*
    分类排序
     */
    public void sorting(Map<Integer,Integer> map) {//
        ArrayList<DishCategory> dishCategories1 = new ArrayList<>();
        for (Integer i : map.keySet()) {
            DishCategory dishCategory = new DishCategory();
            dishCategory.setId(i);
            dishCategory.setCategorySort(map.get(i));
            dishCategories1.add(dishCategory);
        }
        updateBatchById(dishCategories1);
    }
//现在,我们先考虑  创建 一级分类的情况
    public void addBatchCategoriesOne(List<DishCategory> list) {

        //设置fu
        //设置排序
        //查询 排序 最大值
        LambdaQueryWrapper<DishCategory> wrapper = Wrappers.lambdaQuery(DishCategory.class);
        wrapper.eq(DishCategory::getParentCode,"0");
        wrapper.select(DishCategory::getCategorySort).orderByDesc(DishCategory::getCategorySort).last("limit 1");
        Integer categorySort = categoryMapper.selectOne(wrapper).getCategorySort();
        AtomicInteger max= new AtomicInteger(categorySort);
        list.forEach(   one ->   {one.setCategorySort(max.get() +1 );max.addAndGet(1);});
        Stream<DishCategory> stream = list.stream();
        List<DishCategory> collect = stream.map(one -> {
            one.setParentCode("0");
            return one;//
        }).collect(Collectors.toList());
        collect.forEach(System.out::println);
        boolean b = saveBatch(list);
    }

    public void addBatchCategoriesTwo(List<DishCategory> list){
        LambdaQueryWrapper<DishCategory> wrapper = Wrappers.lambdaQuery(DishCategory.class);
        wrapper.eq(DishCategory::getParentCode,list.get(0).getParentCode());
        wrapper.select(DishCategory::getCategorySort).orderByDesc(DishCategory::getCategorySort).last("limit 1");
        Integer categorySort = categoryMapper.selectOne(wrapper).getCategorySort();
        AtomicInteger max= new AtomicInteger(categorySort);
        list.forEach(   one ->   {one.setCategorySort(max.get() +1 );max.addAndGet(1);});
        boolean b = saveBatch(list);

    }

    public void addCategoryLevelOne(DishCategory dishCategory) {
        dishCategory.setParentCode("0");
        boolean save = save(dishCategory);
    }
/*
        查询二级分类 ,根据parent_id;  查询一级分类的子分类
 */
    public List<DishCategory> selectCategoriesLevelTwoByLevelOne(String parentCode){
        LambdaQueryWrapper<DishCategory> wrapper = Wrappers.lambdaQuery(DishCategory.class);
        wrapper.eq(DishCategory::getParentCode,parentCode);
        List<DishCategory> dishCategories = categoryMapper.selectList(wrapper);
return  dishCategories;
    }
/*
创建一级分类
 */
    public void createCategoryOne(DishCategory dishCategory) {
//分类助记码不可超过5位数字 这个要检测
        if(StringUtils.isNotBlank(dishCategory.getMnemonicCode())){
            boolean matches = dishCategory.getMnemonicCode().matches("^\\d{1,5}$");
            if(!matches){
                throw new FailException("分类助记码不可超过5位数字,不可以是汉字字母符号");
            }
        }
        save(dishCategory);
    }

    public void createCategoryTwo(DishCategory param) {

        //  这里组装数据,在这里还是给前端待确定

                     save(param);

    }
    public List<DishCategory> selectCategoriesNoAssociatedDish(){

        LambdaQueryWrapper<DishCategory> wrapper = Wrappers.lambdaQuery(DishCategory.class);
        wrapper.eq(DishCategory::getParentCode, "0");
        wrapper.eq(DishCategory::getAssociatedDishQuantity,0);
        List<DishCategory> dishCategories = categoryMapper.selectList(wrapper);
        return dishCategories;
    }

    public void deleteOneCategory(DishCategory dishCategory) {
        //先判断一下是一级还是二级
  /*一级分类*/      if(dishCategory.getParentCode().equals("0")){
                if(dishCategory.getAssociatedDishQuantity()!=0){
                    throw new FailException("当前分类下有二级分类/菜品，不可删除");    //其实,这里,没有二级分类,只有菜品
                }
            List<DishCategory> dishCategories = selectCategoriesLevelTwoByLevelOne(dishCategory.getCategoryCode());//这个是他这个一级分类下面的二级分类
            if(dishCategories.isEmpty()){
                LambdaQueryWrapper<DishCategory> wrapper = Wrappers.lambdaQuery(DishCategory.class);
                wrapper.eq(DishCategory::getCategoryCode,dishCategory.getCategoryCode());
/*开删!!*/      remove(wrapper);
            }
            //然后去挨个检查,看有没有关联菜品数量
              boolean flag=false;
            for (DishCategory category : dishCategories) {
                Integer associatedDishQuantity = category.getAssociatedDishQuantity();
                if(associatedDishQuantity!=0){
                    flag= true;
                }
            }
            if(flag){
                throw new FailException("当前分类下有二级分类/菜品，不可删除");
            }else{
                // 给出提示     :    删除此分类,关联的二级分类将一同删除,然后删除,注意,这里要顺带删除下面所有的二级分类   TODO
                LambdaQueryWrapper<DishCategory> wrapper = Wrappers.lambdaQuery(DishCategory.class);
                wrapper.eq(DishCategory::getCategoryCode,dishCategory.getCategoryCode());//他自己
                wrapper.eq(DishCategory::getParentCode,dishCategory.getCategoryCode());//他儿子
/*开删!!*/                remove(wrapper);
            }

 /*二级分类*/    }else{
            //判断有没有关联菜品
            if(dishCategory.getAssociatedDishQuantity()!=0){
                throw new FailException("当前分类有菜品,不可以删除~");
            }else{
                LambdaQueryWrapper<DishCategory> wrapper = Wrappers.lambdaQuery(DishCategory.class);
                wrapper.eq(DishCategory::getCategoryCode,dishCategory.getCategoryCode());
/*开删!!*/      remove(wrapper);
            }

        }

    }

    public void editCategory(DishCategory dishCategory) {
        //TODO, 这个要涉及到图片上传.需要进行MINIO的配置

        updateById(dishCategory);




    }

    /*

     */









}


